#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void traverse(char arr[], int size)
{
    for (int i = 0; i < size; i++)
    {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

void swap(void *x, void *y, int size)
{

    char *p = x;
    char *q = y;
    while (size--)
    {
        char temp = *p;
        *p = *q;
        *q = temp;
        p++;
        q++;
    }
}

void bubbleSort(void *arr, int length, int size, int (*compar)(void *a, void *b))
{
    char *arr1 = arr;

    // 优化后的 降序
    for (int i = 0; i < length - 1; i++)
    {

        int flag = 0; // 本轮没有交换位置
        for (int j = 0; j < (length - 1) - i; j++)
        {
            // if (arr[j] - arr[j + 1] < 0)
            if (compar(&arr1[j * size], &arr1[(j + 1) * size]) > 0)
            {
                swap(&arr1[j * size], &arr1[(j + 1) * size], size);

                // 本轮有交换位置
                flag = 1;
            }
        }
        printf("第%d轮排序", i);
        traverse(arr, length);
        if (flag == 0)
        {
            break;
        }
    }
}

int compare(void *a, void *b)
{
    return *(int *)b - *(int *)a;
}

int main()
{
    char arr[] = {4, 1, 3, 1, 5, 2};

    int size = sizeof(arr) / sizeof(arr[0]);
    bubbleSort(arr, size, sizeof(arr[0]), compare);
    traverse(arr, size);

    return 0;
}
